﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Configuration;
using System.IO;
using System.Threading;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using System.Threading.Tasks;
using Common;
using DbControl;
using Models;

namespace CentralMonitoring
{
    public partial class dlgHardInfoV23 : Form
    {
        private MqttClient mqttClient = null;
        public bool IsClose { get; set; } = false;
        private int IsOk = -1;
        private bool IsReady = false;  //下位机是否准备就绪

        delegate void UpdataMessageDelegate(string text, byte[] bytes);
        UpdataMessageDelegate UpdataMessageHandle = null;
        private delegate void ShowTimesDelegate(string strtimes);
        delegate void ShowTextContentDelegate(byte[] array);
        ShowTextContentDelegate ShowTextContentHandle = null;
        delegate void UpdataMsgDelegate(string msg);
        UpdataMsgDelegate UpdataMsgHandle = null;
        
        public dlgHardInfoV23()
        {
            InitializeComponent();
        }
        #region  通信部分
        private void ConnectMqttServer()
        {
            MqttFactory mqttFactory = new MqttFactory();
            if (mqttClient == null)
            {
                mqttClient = (MqttClient)mqttFactory.CreateMqttClient();
                mqttClient.ApplicationMessageReceivedAsync+= MqttClient_ApplicationMessageReceivedAsync;
                mqttClient.ConnectedAsync += MqttClient_ConnectedAsync;
                mqttClient.DisconnectedAsync += MqttClient_DisconnectedAsync;
            }
            ConnectToServer();
        }
        private async void InitMqttServer()
        {
            try
            {
                Task.Run(async () => { ConnectMqttServer(); });
            }
            catch (Exception ex)
            {
                MessageBox.Show("服务启动失败，清重启", "提示");
                lLogWrite.WriteLog("启动服务失败!" + ex.ToString());
            }

        }
        private async void ConnectToServer()
        {
            try
            {
                var mqttClientOptions = new MqttClientOptionsBuilder()
                    .WithTcpServer(session.mServerIp, session.mServerPort) //("101.200.47.148", 1883)
                    .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)
                    .WithClientId(session.mSensorUUID)// + Guid.NewGuid().ToString()"MonitoringApp"
                    .WithCleanSession(false)
                    .WithKeepAlivePeriod(TimeSpan.FromSeconds(30))
                    .WithCredentials("test", "test")
                    .WithCleanSession(true)
                    .Build();

                var res = await mqttClient.ConnectAsync(mqttClientOptions);
            }
            catch (Exception ex)
            {
                Invoke(new Action(() =>
                {
                    textBox1.Text += "状态:连接失败!";
                    lLogWrite.WriteLog("连接失败原因:" + ex.Message);
                }));
            }
        }
        private Task MqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
        {
            if (!IsClose)
            {
                Invoke(new Action(() =>
                {
                    textBox1.Text += "状态:已断开";
                }));
                Invoke(new Action(() =>
                {
                    textBox1.Text += "状态:重连中";
                    lLogWrite.WriteLog("###断开重连###");
                    ConnectToServer();
                }));
            }
            return Task.CompletedTask;

        }
        private Task MqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
        {
            Invoke(new Action(() =>
            {
                textBox1.Text += "状态:已连接";

            }));
            //foreach (Devicelist vo in session.m_dvList)
            //{
            //    if (!string.IsNullOrEmpty(vo.dvTopic))
            //    {
            //        string topic = vo.dvTopic;
            //        mqttClient.SubscribeAsync(topic);
            //    }
            //}
            string topic =session.mSubscribe;
            // topic = "app/update";
            mqttClient.SubscribeAsync(topic);
            lLogWrite.WriteLog(topic);
            return Task.CompletedTask;
        }
        private Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {
            Invoke(new Action(() =>
            {
                //txBMessage.AppendText($">>{Encoding.UTF8.GetString(arg.ApplicationMessage.Payload)}");
                //txBMessage.AppendText($">>{Encoding.Default.GetString(arg.ApplicationMessage.Payload)}");
                //lLogWrite.WriteLog(Encoding.Default.GetString(arg.ApplicationMessage.Payload));
                int n = arg.ApplicationMessage.Payload.Length;
                if (n==5 && arg.ApplicationMessage.Payload[0] == 0xAA && arg.ApplicationMessage.Payload[n - 1] == 0XBB)
                {
                    IsOk = (int)arg.ApplicationMessage.Payload[2];
                    string strLog = "";
                    foreach (byte b in arg.ApplicationMessage.Payload)
                    {
                        strLog = strLog + b.ToString("X2") + " ";
                    }
                    lLogWrite.WriteLog(string.Format("Receive:{0}|{1}", n.ToString(), strLog));
                    Console.WriteLine(strLog);
                }
                else if (n > 0)
                {
                    if (n == 10)
                    {
                        string text = "";
                        try
                        {
                            byte[] NianDu = new byte[4];
                            Array.Copy(arg.ApplicationMessage.Payload, 4, NianDu, 0, 4);
                            Int32 tspan = TimestampHelper.ConvertByteToInt32(NianDu);
                            lLogWrite.WriteLog("时间戳:" + tspan.ToString());
                            DateTime deviceTime = TimestampHelper.GetDateTime((long)tspan);
                            for (int i = 0; i < n; i++)
                            {
                                text = text + arg.ApplicationMessage.Payload[i].ToString("X2") + " ";
                            }
                            lLogWrite.WriteLog(deviceTime.ToString() + "|" + text);
                            ShowTimes(deviceTime.ToString());
                            Invoke(UpdataMessageHandle, text, arg.ApplicationMessage.Payload);
                        }
                        catch (Exception ex)
                        {
                            Invoke(UpdataMessageHandle, ex.ToString(), arg.ApplicationMessage.Payload);
                            lLogWrite.WriteLog(ex.ToString());
                        }
                    }
                    else if (n == 179)
                    {

                        string text = "";
                        for (int i = 0; i < n; i++)
                        {

                            text = text + arg.ApplicationMessage.Payload[i].ToString("X2") + " ";
                        }
                        lLogWrite.WriteLog(text);
                        Invoke(ShowTextContentHandle, arg.ApplicationMessage.Payload);
                    }
                    else
                    {
                        string text = "";
                        for (int i = 0; i < n; i++)
                        {
                            text = text + arg.ApplicationMessage.Payload[i].ToString("X2") + " ";
                        }
                        lLogWrite.WriteLog(text);
                        byte[] buftxt = strToHexByteUTF8(text);
                        text = System.Text.Encoding.Default.GetString(buftxt);
                        if (text.Contains("flag=3"))
                        {
                            IsReady = true;
                        }
                        lLogWrite.WriteLog(text);
                        //  text =System.Text.Encoding.UTF8.GetString(array);
                        Invoke(UpdataMessageHandle, text, arg.ApplicationMessage.Payload);

                        //string orgmsg = System.Text.Encoding.Default.GetString(arg.ApplicationMessage.Payload);
                        //lLogWrite.WriteLog(orgmsg);
                    }
                }               
           }));

            return Task.CompletedTask;
        }
        #endregion
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            if (this.buttonOpen.Text == "启动")
            {
                if (comboBoxDevice.SelectedIndex<1)
                {
                    MessageBox.Show("请选择要升级的终端设备", "提示", MessageBoxButtons.OK);
                    return;
                }
                if (string.IsNullOrEmpty(textBoxSubscribe.Text))
                {
                    MessageBox.Show("请输入订阅识别码", "提示", MessageBoxButtons.OK);
                    return;
                }           
                
                if (!string.IsNullOrEmpty(textBoxSubscribe.Text))
                {
                    session.mSensorUUID = GetRandNum() + textBoxSubscribe.Text;// "0000"
                }
                sensors sensor = OprSensor.GetSensorByCode(comboBoxDevice.SelectedValue.ToString());
                session.mTopic = textBoxSubscribe.Text+ session.mTopic ;
                session.mSubscribe =  textBoxSubscribe.Text +session.mSubscribe;
                session.mTopic = sensor.sensor_subscribe; 
                session.mSubscribe = sensor.sensor_topic;
                string sResult = "";
                try
                {
                    InitMqttServer();
                    this.StatusLabelPump.Text = string.Format("状态:{0}", "已连接");
                    this.buttonOpen.Text = "关闭";
                    setButton(true);
                }
                catch (Exception ee)
                {
                    setButton(false);
                    this.StatusLabelPump.Text = string.Format("状态:{0}", "未连接");
                    MessageBox.Show(ee.ToString());
                }
            }
            else
            {
                if (mqttClient != null && mqttClient.IsConnected)
                {
                    IsClose = true;
                    mqttClient.DisconnectAsync();
                    mqttClient.Dispose();
                    mqttClient = null;
                    this.buttonOpen.Text = "启动";
                    setButton(false);
                    ResetTopicAndSub();
                }
            }              
        }
        private void ResetTopicAndSub()
        {
            session.mSubscribe = "/up";
            session.mTopic = "/down";
        }
        private string GetRandNum()
        {
            Random rand = new Random();
            return rand.Next(1000, 9999).ToString();
        }
        private void YTdlgHardInfo_Load(object sender, EventArgs e)
        {
            StatusLabel0.Text = DateTime.Now.ToString("系统时间：yyyy-MM-dd HH:mm:ss");
            InitCombox();
            //初始化控件
            UpdataMessageHandle = new UpdataMessageDelegate(UpdateShowMessage);
            ShowTextContentHandle = new ShowTextContentDelegate(ShowTextBoxContent);
            UpdataMsgHandle=new UpdataMsgDelegate(UpdateShowMsg);
            setButton(false); 
            panelHide.Height = 6;
            this.WindowState = FormWindowState.Maximized;            
        }
        private void InitCombox()
        {
            DataTable dt = OprDeviceConfig.GetDeviceBySensors();
            if (dt != null)
            {
                DataRow row = dt.NewRow();             
                row["sensor_code"] = "0";
                row["device_name"] = "请选择";
                dt.Rows.InsertAt(row, 0);                
                comboBoxDevice.DisplayMember = "device_name";
                comboBoxDevice.ValueMember = "sensor_code";
                comboBoxDevice.DataSource = dt;
                comboBoxDevice.SelectedIndex = 0;
            }
        }
        private int byteTointXB(byte[] b)
        {

            int j = 0; 
            j = (int)b[1];
            j += (int)b[0] << 8;
            j += (int)b[3] << 16;
            j += (int)b[2] << 24;

            return j;
        }
        void UpdateShowMessage(string text, byte[] bytes)//显示接收消息
        {  
            if (bytes != null)
            {
                string stringBuilder = ""; 
                for (int i = 0; i < bytes.Length; i++)
                {
                    stringBuilder = stringBuilder + bytes[i].ToString("X2") + " ";
                }
                string s=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                text = text.Replace("\n", Environment.NewLine);
                s+="|";
                s+=text;
                s+="\r\n";
                textBox1.Text = s+ textBox1.Text; 
            }            
        }
        void UpdateShowMsg(string msg)
        {
            string s = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            s += "|";
            s += msg;
            s += "\r\n";
            textBox1.Text = s + textBox1.Text;
        }
        //字符串转16进制字节数组
        private  byte[] strToHexByteUTF8(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
   
        //16进制字符串转字节数组
        private static byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
        public void SendPublic(byte[] data)
        {
            var message = new MqttApplicationMessage
            {
                Topic = session.mTopic,
                //Payload = Encoding.Default.GetBytes(data),
                Payload = data,
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                Retain = false,
            };
            if (mqttClient != null)
            {
                mqttClient.PublishAsync(message);
                IsOk = -1;
            }
        }
        private void sendCmd(byte[] data)
        {
            var message = new MqttApplicationMessage
            {
                Topic = session.mTopic,
                //Payload = Encoding.Default.GetBytes(data),
                Payload = data,
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                Retain = false,
            };
            if (mqttClient != null)
            {
                mqttClient.PublishAsync(message);               
            }

        } 
       
        public void setButton(bool b)
        { 
            this.buttonSetTime.Enabled = b;
            this.buttonGetTime.Enabled = b;
            this.buttonSetParam.Enabled = b;
            this.buttonReadParam.Enabled = b;
            this.buttonFind.Enabled = b;
            this.buttonUpdate.Enabled = b;
            this.btnReset.Enabled = b;

        }  

        private void timer2_Tick(object sender, EventArgs e)
        {
            StatusLabel0.Text = DateTime.Now.ToString("系统时间：yyyy-MM-dd HH:mm:ss");   
        }

        private void buttonQuery_Click(object sender, EventArgs e)
        {           
            //string send201 = "{\"method\":\"report\",\"report_type\":201,\"data\":{\"mac\":\"4ed50715-bbcf-257c-ac24-2101a3e2a742\",\"status\":\"normal\",\"gateway_mac\": \"4ed50715-bbcf-257c-ac24-2101\",\"Fe_type\":\"Fe1,Fe2,Fe3,Fe4,Fe5,Fe6,Fe7,Fe8,Fe9,Fe10\",\"MFe_type\":\"MFe1,MFe2,MFe3,MFe4,MFe5,MFe6,MFe7,MFe8,MFe9,MFe10\",\"NFe_type\":\"NFe1,NFe2,NFe3,NFe4,NFe5,NFe6,NFe7,NFe8,NFe9,NFe10\",\"Mo_type\":\"Mo\",\"Vis_type\":\"Vis\",\"Dens_type\":\"Dens\",\"Diel_type\":\"Diel\",\"Temp_type\":\"Temp\"}}";
            //byte[] sendbytes = System.Text.Encoding.Default.GetBytes(send201);            
            //this.sendCmd(sendbytes);
            //textBox1.Text += send201;
            //textBox1.Text += "\r\n";   
            //System.Threading.Thread.Sleep(1000);
            //checkBox1.Checked = true;
             List<byte> list = new List<byte>();
            list.InsertRange(0, new byte[] { 0XFF, 0X47, 0X00, 0X01, 0X41, 0XE5 });
            this.sendCmd(list.ToArray());
            
        }

        private void buttonClear_Click(object sender, EventArgs e)
        {
            this.textBox1.Clear();

            //decimal d_tmp = new Random().Next(100, 600) / (decimal)10;
            //decimal d_vis = new Random().Next(600, 1000) / (decimal)10;
            //decimal d_Diel = new Random().Next(800,999) / (decimal)1000;
            //decimal d_Jdcs = new Random().Next(20000, 30000) / (decimal)10000;
            //textBox1.Text = d_Jdcs.ToString();
        }
        private  byte[] HighToLow(byte[] b)
        {
            List<byte> l = new List<byte>();
            l.Add(b[3]);
            l.Add(b[2]);
            l.Add(b[1]);
            l.Add(b[0]);
            return l.ToArray();
        }

        private void buttonGetTime_Click(object sender, EventArgs e)
        {
            //Int32 dd = TimestampHelper.Toint32(DateTime.Now);
            //DateTime dt2 = TimestampHelper.GetDateTime((long)dd);
            //MessageBox.Show(dd.ToString()+"\r\n"+dt2.ToString());

            List<byte> list = new List<byte>();
            list.InsertRange(0, new byte[] { 0XFF, 0X04, 0X00, 0X00, 0X00, 0X02, 0X64, 0X15 });
            string text = "";
            foreach (byte b in list)
            {
                text = text + b.ToString("X2") + " "; 
            }
            lLogWrite.WriteLog("请求时间:" + text);
            this.sendCmd(list.ToArray());
            list.Clear();  
   
        }

        private void buttonSetTime_Click(object sender, EventArgs e)
        {
            Int32 dd = TimestampHelper.Toint32(DateTime.Now);
            lLogWrite.WriteLog("当前时间戳:"+dd.ToString());
            byte[] arry = TimestampHelper.ConvertIntToByteArray(dd);
            string txt = "";
            foreach (byte b in arry)
            {
                txt = txt + b.ToString("X2") + " "; 
            }
            lLogWrite.WriteLog("时间转换成字节:"+txt);
            List<byte> list = new List<byte>();
            list.AddRange(new byte[] { 0XFF, 0X05, 0X00, 0X00, 0X00, 0X02, 0X04});
            list.AddRange(arry);
            txt = "";
            foreach (byte b in list)
            {
                txt = txt + b.ToString("X2") + " ";
            }
            lLogWrite.WriteLog("字节:" + txt);
            byte[] crc16 = TimestampHelper.ToModbus(list.ToArray());
            list.AddRange(crc16);
            txt = "";
            foreach (byte b in list)
            {
                txt = txt + b.ToString("X2") + " ";
            }
            lLogWrite.WriteLog("时间转换成字节:" + txt);
            this.sendCmd(list.ToArray());
        }
        private void ShowTimes(string strtimes)
        {
            if (this.InvokeRequired)
                this.BeginInvoke(new ShowTimesDelegate(ShowTimes), strtimes);
            else
            {
                textBoxTimes.Text = strtimes;
            }
        }

        private void buttonReadParam_Click(object sender, EventArgs e)
        {
            List<byte> list = new List<byte>();
            //list.InsertRange(0, new byte[] { 0XFF, 0X03,0X00, 0X00, 0X00, 0X3F, 0X10, 0X04 });
            list.InsertRange(0, new byte[] { 0XFF, 0X03, 0X00, 0X00, 0X00, 0X57, 0X11, 0XEA });
            this.sendCmd(list.ToArray());
        }

        private void ShowTextBoxContent(byte[] array)
        {
            try
            {
                string text = "";
                for (int i = 0; i < array.Length; i++)
                {

                    text = text + array[i].ToString("X2") + " ";
                }
                lLogWrite.WriteLog(text);
                byte[] gateMac = new byte[18];
                byte[] sensor1Mac = new byte[8];
                byte[] sensor2Mac = new byte[8];
                byte[] gateAdd = new byte[2];
                byte[] sensor1Status = new byte[2];
                byte[] sensor2Status = new byte[2];
                byte[] sensor1Times = new byte[2];
                byte[] sensor2Times = new byte[2];
                byte[] power1Status = new byte[2];
                byte[] power2Status = new byte[2];
                byte[] power1Direct = new byte[2];
                byte[] power2Direct = new byte[2];
                byte[] power1Speed = new byte[2];
                byte[] power2Speed = new byte[2];
                byte[] sensor1Value = new byte[2];
                byte[] sensor2Value = new byte[2];
                byte[] sensorYlzs = new byte[2];

                byte[] sensor1Temper = new byte[2];
                byte[] sensor2Temper = new byte[2];
                byte[] sensor1VisXSa = new byte[4];
                byte[] sensor1VisXSb = new byte[4];
                byte[] sensor2VisXSa = new byte[4];
                byte[] sensor2VisXSb = new byte[4];
                byte[] sensor1VisBL = new byte[2];
                byte[] sensor2VisBL = new byte[2];
                byte[] sensor1Vis = new byte[2];
                byte[] sensor2Vis = new byte[2];
                byte[] sensor1Midu = new byte[2];
                byte[] sensor2Midu = new byte[2];
                byte[] sensor1Aw = new byte[2];
                byte[] sensor2Aw = new byte[2];
                byte[] sensor1Ppm = new byte[2];
                byte[] sensor2Ppm = new byte[2];
                byte[] sensor1Hsl = new byte[2];
                byte[] sensor2Hsl = new byte[2];
                byte[] sensor1Jdcs = new byte[2];
                byte[] sensor2Jdcs = new byte[2];
                byte[] sensor1YSQDSJ = new byte[2];
                byte[] sensor2YSQDSJ = new byte[2];
                byte[] sensor1YSQDZS = new byte[2];
                byte[] sensor2YSQDZS = new byte[2];
                byte[] sensor1QDYXSJ = new byte[2];
                byte[] sensor2QDYXSJ = new byte[2];
                byte[] sensorGJGNXS = new byte[2];
                byte[] sensorMsgBack = new byte[2];
                byte[] sensorTopic=new byte[14];
                byte[] sensorDeviceId=new byte[32];


                Array.Copy(array, 3, gateMac, 0, 18);
                Array.Copy(array, 21, sensor1Mac, 0, 8);
                Array.Copy(array, 29, sensor2Mac, 0, 8);
                Array.Copy(array, 37, gateAdd, 0, 2);
                Array.Copy(array, 39, sensor1Status, 0, 2);
                Array.Copy(array, 41, sensor2Status, 0, 2);
                Array.Copy(array, 43, sensor1Times, 0, 2);
                Array.Copy(array, 45, sensor2Times, 0, 2);
                Array.Copy(array, 47, power1Status, 0, 2);
                Array.Copy(array, 49, power2Status, 0, 2);
                Array.Copy(array, 51, power1Direct, 0, 2);
                Array.Copy(array, 53, power2Direct, 0, 2);
                Array.Copy(array, 55, power1Speed, 0, 2);
                Array.Copy(array, 57, power2Speed, 0, 2);
                Array.Copy(array, 59, sensor1Value, 0, 2);
                Array.Copy(array, 61, sensor2Value, 0, 2);
                Array.Copy(array, 63, sensorYlzs, 0, 2);
                Array.Copy(array, 65, sensor1Temper, 0, 2);
                Array.Copy(array, 67, sensor2Temper, 0, 2);
                Array.Copy(array, 69, sensor1VisXSa, 0, 4);
                Array.Copy(array, 73, sensor1VisXSb, 0, 4);
                Array.Copy(array, 77, sensor2VisXSa, 0, 4);
                Array.Copy(array, 81, sensor2VisXSb, 0, 4);
                Array.Copy(array, 85, sensor1VisBL, 0, 2);
                Array.Copy(array, 87, sensor2VisBL, 0, 2);
                Array.Copy(array, 89, sensor1Vis, 0, 2);
                Array.Copy(array, 91, sensor2Vis, 0, 2);
                Array.Copy(array, 93, sensor1Midu, 0, 2);
                Array.Copy(array, 95, sensor2Midu, 0, 2);
                Array.Copy(array, 97, sensor1Aw, 0, 2);
                Array.Copy(array, 99, sensor2Aw, 0, 2);
                Array.Copy(array, 101, sensor1Ppm, 0, 2);
                Array.Copy(array, 103, sensor2Ppm, 0, 2);
                Array.Copy(array, 105, sensor1Hsl, 0, 2);
                Array.Copy(array, 107, sensor2Hsl, 0, 2);
                Array.Copy(array, 109, sensor1Jdcs, 0, 2);
                Array.Copy(array, 111, sensor2Jdcs, 0, 2);
                Array.Copy(array, 113, sensor1YSQDSJ, 0, 2);
                Array.Copy(array, 115, sensor2YSQDSJ, 0, 2);
                Array.Copy(array, 117, sensor1YSQDZS, 0, 2);
                Array.Copy(array, 119, sensor2YSQDZS, 0, 2);
                Array.Copy(array, 121, sensor1QDYXSJ, 0, 2);
                Array.Copy(array, 123, sensor2QDYXSJ, 0, 2);
                Array.Copy(array, 125, sensorGJGNXS, 0, 2);
                Array.Copy(array, 127, sensorMsgBack, 0, 2);
                Array.Copy(array, 129, sensorTopic, 0, 14);
                Array.Copy(array, 143, sensorDeviceId, 0, 32);
                
                string strGateWayMac= System.Text.Encoding.ASCII.GetString(gateMac);
                this.textBoxGateWayMAC.Text = strGateWayMac.Substring(0, strGateWayMac.Length - 1);

                string strSensor1Mac=System.Text.Encoding.ASCII.GetString(sensor1Mac);
                this.textBoxSensor1Mac.Text=strSensor1Mac;
                string strSensor2Mac=System.Text.Encoding.ASCII.GetString(sensor2Mac);
                this.textBoxSensor2Mac.Text=strSensor2Mac;

                UInt16 igateAdd = BitConverter.ToUInt16(gateAdd,0);
                this.textBoxGateWayAdd.Text = igateAdd.ToString();

                UInt16 isensor1Status = BitConverter.ToUInt16(sensor1Status,0);
                this.textBoxSensor1Status.Text = isensor1Status.ToString();

                UInt16 isensor2Status = BitConverter.ToUInt16(sensor2Status, 0);
                this.textBoxSensor2Status.Text = isensor2Status.ToString();

                UInt16 isensor1Times = BitConverter.ToUInt16(sensor1Times, 0);
                this.textBoxSensor1Time.Text = isensor1Times.ToString();

                UInt16 isensor2Times = BitConverter.ToUInt16(sensor2Times, 0);
                this.textBoxSensor2Times.Text = isensor2Times.ToString();

                UInt16 ipower1Status = BitConverter.ToUInt16(power1Status, 0);
                this.textBoxDJ1Status.Text = ipower1Status.ToString();

                UInt16 ipower2Status = BitConverter.ToUInt16(power2Status, 0);
                this.textBoxDJ2Status.Text = ipower2Status.ToString();

                UInt16 ipower1Direct = BitConverter.ToUInt16(power1Direct, 0);
                this.textBoxDJ1Pos.Text = ipower1Direct.ToString();

                UInt16 ipower2Direct = BitConverter.ToUInt16(power2Direct, 0);
                this.textBoxDJ2Pos.Text = ipower2Direct.ToString();

                UInt16 ipower1Speed = BitConverter.ToUInt16(power1Speed, 0);
                this.textBoxDJ1Speed.Text = ipower1Speed.ToString();

                UInt16 ipower2Speed = BitConverter.ToUInt16(power2Speed, 0);
                this.textBoxDJ2Speed.Text = ipower2Speed.ToString();

                UInt16 isensor1Value = BitConverter.ToUInt16(sensor1Value, 0);
                this.textBoxSensor1Value.Text = isensor1Value.ToString();

                UInt16 isensor2Value = BitConverter.ToUInt16(sensor2Value, 0);
                this.textBoxSensor2Value.Text = isensor2Value.ToString();

                UInt16 isensorYlzs = BitConverter.ToUInt16(sensorYlzs,0);
                this.textBoxYlzh.Text = isensorYlzs.ToString();

                //2022.10.18新增参数调整
                decimal isensor1Temper =(decimal)BitConverter.ToInt16(sensor1Temper,0);
                this.txbSensor1Temper.Text =decimal.Round(isensor1Temper/10,1).ToString();
                decimal isensor2Temper = (decimal)BitConverter.ToInt16(sensor2Temper,0);
                this.txbSensor2Temper.Text =decimal.Round(isensor2Temper/10,1).ToString();

                decimal isensor1VisQXa = (decimal)BitConverter.ToUInt32(sensor1VisXSa,0);
                this.txbSensor1VisXa.Text=decimal.Round(isensor1VisQXa/1000000,6).ToString();
                decimal isensor1VisQXb=(decimal)BitConverter.ToUInt32(sensor1VisXSb,0);
                this.txbSensor1VisXb.Text=decimal.Round(isensor1VisQXb/1000000,6).ToString();
                decimal isensor2VisQXa = (decimal)BitConverter.ToUInt32(sensor2VisXSa,0);
                this.txbSensor2VisXa.Text=decimal.Round(isensor2VisQXa/1000000,6).ToString();
                decimal isensor2VisQXb = (decimal)BitConverter.ToUInt32(sensor2VisXSb,0);
                this.txbSensor2VisXb.Text=decimal.Round(isensor2VisQXb/1000000,6).ToString();
                int isensor1VisBl=byteToint(sensor1VisBL);
                this.txbSensor1VisBl.Text=isensor1VisBl.ToString();
                int isensor2VisBl=byteToint(sensor2VisBL);
                this.txbSensor2VisBl.Text=isensor2VisBl.ToString();
                decimal dsensor1Vis = (decimal)BitConverter.ToInt16(sensor1Vis,0);
                this.txbSensor1Vis.Text = decimal.Round(dsensor1Vis / 100, 2).ToString();
                decimal dsensor2Vis = (decimal)BitConverter.ToInt16(sensor2Vis,0);
                this.txbSensor2Vis.Text = decimal.Round(dsensor2Vis / 10, 1).ToString();
                decimal dsensor1Midu = (decimal)BitConverter.ToInt16(sensor1Midu,0);
                this.txbSensor1Midu.Text = decimal.Round(dsensor1Midu / 1000, 3).ToString();
                decimal dsensor2Midu = (decimal)BitConverter.ToInt16(sensor2Midu,0);
                this.txbSensor2Midu.Text = decimal.Round(dsensor2Midu / 10,1).ToString();
                decimal dsensor1AW = (decimal)BitConverter.ToInt16(sensor1Aw,0);
                this.txbSensor1AW.Text = decimal.Round(dsensor1AW / 100, 2).ToString();
                decimal dsensor2AW = (decimal)BitConverter.ToInt16(sensor2Aw,0);
                this.txbSensor2AW.Text = decimal.Round(dsensor2AW / 100, 2).ToString();
                Int16 isensor1ppm = BitConverter.ToInt16(sensor1Ppm,0);
                this.txbSensor1PPM.Text = isensor1ppm.ToString();
                Int16 isensor2ppm = BitConverter.ToInt16(sensor2Ppm, 0);
                this.txbSensor2PPM.Text = isensor2ppm.ToString();
                decimal dsensor1Hsl = (decimal)BitConverter.ToInt16(sensor1Hsl,0);
                this.txbSensor1Hsl.Text = decimal.Round(dsensor1Hsl / 100, 2).ToString();
                decimal dsensor2Hsl = (decimal)BitConverter.ToInt16(sensor2Hsl,0);
                this.txbSensor2Hsl.Text = decimal.Round(dsensor2Hsl / 100, 2).ToString();
                decimal dsensor1Jdcs = (decimal)BitConverter.ToInt16(sensor1Jdcs,0);
                this.txbSensor1Jdcs.Text = decimal.Round(dsensor1Jdcs / 1000, 3).ToString();
                UInt16 dsensor2Jdcs = BitConverter.ToUInt16(sensor2Jdcs,0);
                this.txbSensor2Jdcs.Text = dsensor2Jdcs.ToString();
                UInt16 isensor1YSQDSJ = BitConverter.ToUInt16(sensor1YSQDSJ,0);
                this.txbSensor1YSQDSJ.Text = isensor1YSQDSJ.ToString();
                UInt16 isensor2YSQDSJ = BitConverter.ToUInt16(sensor2YSQDSJ, 0);
                this.txbSensor2YSQDSJ.Text = isensor2YSQDSJ.ToString();
                UInt16 isensor1YSQDZS = BitConverter.ToUInt16(sensor1YSQDZS, 0);
                this.txbSensor1YSQDZS.Text = isensor1YSQDZS.ToString();
                UInt16 isensor2YSQDZS = BitConverter.ToUInt16(sensor2YSQDZS, 0);
                this.txbSensor2YSQDZS.Text = isensor2YSQDZS.ToString();
                UInt16 isensor1QDYXSJ = BitConverter.ToUInt16(sensor1QDYXSJ, 0);
                this.txbSensor1QDYXSJ.Text = isensor1QDYXSJ.ToString();
                UInt16 isensor2QDYXSJ = BitConverter.ToUInt16(sensor2QDYXSJ, 0);
                this.txbSensor2QDYXSJ.Text = isensor2QDYXSJ.ToString();

                UInt16 iMargdisplay = BitConverter.ToUInt16(sensorGJGNXS, 0);
                this.txbSensorMargDisply.Text = iMargdisplay.ToString();
                UInt16 iMsgBack = BitConverter.ToUInt16(sensorMsgBack, 0);
                this.txbSensorMsgBack.Text = iMsgBack.ToString();
                //2022.12.03
                string strTopic = System.Text.Encoding.ASCII.GetString(sensorTopic);
                this.textBoxtopic.Text = strTopic.Substring(0, strTopic.Length - 1);
                string strDeviceId=System.Text.Encoding.ASCII.GetString(sensorDeviceId);
                this.textBoxDeviceId.Text=strDeviceId.TrimEnd('?');

                
                //Invoke(UpdataMessageHandle, stringBuilder.ToString(), array);
            }
            catch (Exception ex)
            {
                lLogWrite.WriteLog("解析有误:"+ex.ToString());
            }
 
        }
        private int byteToint(byte[] b)
        {
            int j = 0;
            j += (int)b[1]<<8;
            j += (int)b[0];            
            return j;
        }
        private int byteToUint(byte[] b)
        {
            return BitConverter.ToUInt16(b, 0);
        }

        private void buttonSetParam_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(textBoxGateWayMAC.Text))
            {
                MessageBox.Show("请输入网关MAC码", "提示", MessageBoxButtons.OK);
                return;               
            }
            if(textBoxGateWayMAC.Text.Length!=17)
            {
                MessageBox.Show("网关MAC码长度不符（网关码17位)", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxGateWayAdd.Text))
            {
                MessageBox.Show("请输入网关地址", "提示", MessageBoxButtons.OK);
                return;               
            }
            if (string.IsNullOrEmpty(textBoxDJ1Status.Text))
            {
                MessageBox.Show("请输入伺服电机1启用状态", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxDJ1Pos.Text))
            {
                MessageBox.Show("请输入伺服电机1正反转状态", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxDJ1Speed.Text))
            {
                MessageBox.Show("请输入伺服电机1转速", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxDJ2Status.Text))
            {
                MessageBox.Show("请输入伺服电机2启用状态", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxDJ2Pos.Text))
            {
                MessageBox.Show("请输入伺服电机2正反转状态", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxDJ2Speed.Text))
            {
                MessageBox.Show("请输入伺服电机2转速", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxSensor1Mac.Text))
            {
                MessageBox.Show("请输入传感器1MAC码", "提示", MessageBoxButtons.OK);
                return;
            }
            if (textBoxSensor1Mac.Text.Length != 8)
            {
                MessageBox.Show("传感器1MAC码长度不符（传感器MAC码8位)", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxSensor1Status.Text))
            {
                MessageBox.Show("请输入传感器1启用状态", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxSensor1Time.Text))
            {
                MessageBox.Show("请输入传感器1检测间隔", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxSensor1Value.Text))
            {
                MessageBox.Show("请输入传感器1修正值", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxSensor2Mac.Text))
            {
                MessageBox.Show("请输入传感器2MAC码", "提示", MessageBoxButtons.OK);
                return;
            }
            if (textBoxSensor2Mac.Text.Length != 8)
            {
                MessageBox.Show("传感器2MAC码长度不符（传感器MAC码8位)", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxSensor2Status.Text))
            {
                MessageBox.Show("请输入传感器2启用状态", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxSensor2Times.Text))
            {
                MessageBox.Show("请输入传感器2检测间隔", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxSensor2Value.Text))
            {
                MessageBox.Show("请输入传感器2修正值", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(textBoxYlzh.Text))
            {
                MessageBox.Show("请输入油路转换时间参数值", "提示", MessageBoxButtons.OK);
                return;
            }
            if (textBoxtopic.Text.Length > 14)
            {
                MessageBox.Show("Topic不能超过14个字符", "提示", MessageBoxButtons.OK);
                return;
            }
            if (textBoxDeviceId.Text.Length > 32)
            {
                MessageBox.Show("设备ID不能超过32个字符", "提示", MessageBoxButtons.OK);
                return;
            }
            this.sendCmd(SetParmbyt());
        }
        private static byte[] int2bytes(Int16 intValue)
        {
            byte[] intBytes = BitConverter.GetBytes(intValue);
            //if (BitConverter.IsLittleEndian)
            //    Array.Reverse(intBytes);
            byte[] result = intBytes;
            return result;
        }
        private static byte[] Uint2bytes(UInt16 intValue)
        {
            byte[] intBytes = BitConverter.GetBytes(intValue);
            //if (BitConverter.IsLittleEndian)
            //    Array.Reverse(intBytes);
            byte[] result = intBytes;
            return result;
        }
        private static byte[] Uint32bytes(UInt32 intValue)
        {
            byte[] intBytes = BitConverter.GetBytes(intValue);
            //if (BitConverter.IsLittleEndian)
            //    Array.Reverse(intBytes);
            byte[] result = intBytes;
            return result;
        }
        private byte[] SetParmbyt()
        {
            List<byte> list = new List<byte>();
            //list.AddRange(new byte[] { 0XFF, 0X10, 0X00, 0X00, 0X00, 0X1F, 0X3E });
            //list.AddRange(new byte[] { 0XFF, 0X10, 0X00, 0X00, 0X00, 0X3F, 0X7E });
            list.AddRange(new byte[] { 0XFF, 0X10, 0X00, 0X00, 0X00, 0X57, 0XAE });

            string strGateWayMac =this.textBoxGateWayMAC.Text+"0" ;
            byte[] gateMac = System.Text.Encoding.Default.GetBytes(strGateWayMac);
            list.AddRange(gateMac);

            string strSensor1Mac =  this.textBoxSensor1Mac.Text;
            byte[] sensor1Mac = System.Text.Encoding.Default.GetBytes(strSensor1Mac);
            list.AddRange(sensor1Mac);

            string strSensor2Mac = this.textBoxSensor2Mac.Text;
            byte[] sensor2Mac = System.Text.Encoding.Default.GetBytes(strSensor2Mac);
            list.AddRange(sensor2Mac);

            UInt16 igateAdd = UInt16.Parse(textBoxGateWayAdd.Text);
            byte[] gateAdd=Uint2bytes(igateAdd);
            list.AddRange(gateAdd);

            UInt16 isensor1Status = UInt16.Parse(textBoxSensor1Status.Text.Trim());
            byte[] sensor1Status = Uint2bytes(isensor1Status);
            list.AddRange(sensor1Status);

            UInt16 isensor2Status = UInt16.Parse(textBoxSensor2Status.Text.Trim());
            byte[] sensor2Status = Uint2bytes(isensor2Status);
            list.AddRange(sensor2Status);

            UInt16 isensor1Times = UInt16.Parse(textBoxSensor1Time.Text.Trim());
            byte[] sensor1Times = Uint2bytes(isensor1Times);
            list.AddRange(sensor1Times);

            UInt16 isensor2Times = UInt16.Parse(textBoxSensor2Times.Text.Trim());
            byte[] sensor2Times = Uint2bytes(isensor2Times);
            list.AddRange(sensor2Times);

            UInt16 ipower1Status = UInt16.Parse(textBoxDJ1Status.Text.Trim());
            byte[] power1Status = Uint2bytes(ipower1Status);
            list.AddRange(power1Status);

            UInt16 ipower2Status = UInt16.Parse(textBoxDJ2Status.Text.Trim());
            byte[] power2Status = Uint2bytes(ipower2Status);
            list.AddRange(power2Status);

            UInt16 ipower1Direct = UInt16.Parse(textBoxDJ1Pos.Text.Trim());
            byte[] power1Direct = Uint2bytes(ipower1Direct);
            list.AddRange(power1Direct);

            UInt16 ipower2Direct = UInt16.Parse(textBoxDJ2Pos.Text.Trim());
            byte[] power2Direct = Uint2bytes(ipower2Direct);
            list.AddRange(power2Direct);

            UInt16 ipower1Speed = UInt16.Parse(textBoxDJ1Speed.Text.Trim());
            byte[] power1Speed = Uint2bytes(ipower1Speed);
            list.AddRange(power1Speed);

            UInt16 ipower2Speed = UInt16.Parse(textBoxDJ2Speed.Text);
            byte[] power2Speed = Uint2bytes(ipower2Speed);
            list.AddRange(power2Speed);

            UInt16 isensor1Value = UInt16.Parse(textBoxSensor1Value.Text);
            byte[] sensor1Value = Uint2bytes(isensor1Value);
            list.AddRange(sensor1Value);

            UInt16 isensor2Value = UInt16.Parse(textBoxSensor2Value.Text);
            byte[] sensor2Value = Uint2bytes(isensor2Value);
            list.AddRange(sensor2Value);

            UInt16 ylZhuanHuan = UInt16.Parse(textBoxYlzh.Text);
            byte[] ylArray = Uint2bytes(ylZhuanHuan);
            list.AddRange(ylArray);

            #region 参数调整部分
            Int16 isensor1Temper = (Int16) (decimal.Parse(txbSensor1Temper.Text)*10);
            byte[] sensor1Temper = int2bytes(isensor1Temper);
            list.AddRange(sensor1Temper);
            Int16 isensor2Temper = (Int16)(decimal.Parse(txbSensor2Temper.Text)*10);
            byte[] sensor2Temper = int2bytes(isensor2Temper);
            list.AddRange(sensor2Temper);

            UInt32 isensor1VisQXa =(UInt32)(decimal.Parse(txbSensor1VisXa.Text)*1000000);
            byte[] sensor1VisQXa = Uint32bytes(isensor1VisQXa);
            list.AddRange(sensor1VisQXa);
            UInt32 isensor1VisQXb = (UInt32)(decimal.Parse(txbSensor1VisXb.Text)*1000000);
            byte[] sensor1VisQXb = Uint32bytes(isensor1VisQXb);
            list.AddRange(sensor1VisQXb);
            UInt32 isensor2VisQXa = (UInt32)(decimal.Parse(txbSensor2VisXa.Text)*1000000);
            byte[] sensor2VisQXa = Uint32bytes(isensor2VisQXa);
            list.AddRange(sensor2VisQXa);
            UInt32 isensor2VisQXb = (UInt32)(decimal.Parse(txbSensor2VisXb.Text)*1000000);
            byte[] sensor2VisQXb = Uint32bytes(isensor2VisQXb);
            list.AddRange(sensor2VisQXb);
            UInt16 isensor1VisBl = UInt16.Parse(txbSensor1VisBl.Text);
            byte[] sensor1VisBl = Uint2bytes(isensor1VisBl);
            list.AddRange(sensor1VisBl);
            UInt16 isensor2VisBl = UInt16.Parse(txbSensor2VisBl.Text);
            byte[] sensor2VisBl = Uint2bytes(isensor2VisBl);
            list.AddRange(sensor2VisBl);

            Int16 isensor1Vis =(Int16) (decimal.Parse(txbSensor1Vis.Text)* 100);
            byte[] sensor1Vis = int2bytes(isensor1Vis);
            list.AddRange(sensor1Vis);
            Int16 isensor2Vis=(Int16)(decimal.Parse(txbSensor2Vis.Text)* 10);
            byte[] sensor2Vis = int2bytes(isensor2Vis);
            list.AddRange(sensor2Vis);
            Int16  isensor1Midu=(Int16)(decimal.Parse(txbSensor1Midu.Text)* 1000);
            byte[] sensor1Midu = int2bytes(isensor1Midu);
            list.AddRange(sensor1Midu);
            Int16 isensor2Midu = (Int16)(decimal.Parse(txbSensor2Midu.Text) * 10);
            byte[] sensor2Midu = int2bytes(isensor2Midu);
            list.AddRange(sensor2Midu);
            Int16 isensor1AW =(Int16)(decimal.Parse(txbSensor1AW.Text)*100);
            byte[] sensor1AW = int2bytes(isensor1AW);
            list.AddRange(sensor1AW);
            Int16 isensor2AW =(Int16)(decimal.Parse(txbSensor2AW.Text)* 100);
            byte[] sensor2AW = int2bytes(isensor2AW);
            list.AddRange(sensor2AW);
            Int16 isensor1ppm=Int16.Parse(txbSensor1PPM.Text);
            byte[] sensor1ppm = int2bytes(isensor1ppm);
            list.AddRange(sensor1ppm);
            Int16 isensor2ppm = Int16.Parse(txbSensor2PPM.Text);
            byte[] sensor2ppm = int2bytes(isensor2ppm);
            list.AddRange(sensor2ppm);
            Int16 dsensor1Hsl =(Int16)(decimal.Parse(txbSensor1Hsl.Text)*100);
            byte[] sensor1Hsl = int2bytes(dsensor1Hsl);
            list.AddRange(sensor1Hsl);
            Int16 dsensor2Hsl = (Int16)(decimal.Parse(txbSensor2Hsl.Text)* 100);
            byte[] sensor2Hsl = int2bytes(dsensor2Hsl);
            list.AddRange(sensor2Hsl);
            Int16 dsensor1Jdcs =(Int16)(decimal.Parse(txbSensor1Jdcs.Text)*1000);
            byte[] sensor1Jdcs = int2bytes(dsensor1Jdcs);
            list.AddRange(sensor1Jdcs);
            UInt16 dsensor2Jdcs = UInt16.Parse(txbSensor2Jdcs.Text);
            byte[] sensor2Jdcs = Uint2bytes(dsensor2Jdcs);
            list.AddRange(sensor2Jdcs);
            UInt16 isensor1YSQDSJ = UInt16.Parse(txbSensor1YSQDSJ.Text);
            byte[] sensor1YSQDSJ = Uint2bytes(isensor1YSQDSJ);
            list.AddRange(sensor1YSQDSJ);
            UInt16 isensor2YSQDSJ = UInt16.Parse(txbSensor2YSQDSJ.Text);
            byte[] sensor2YSQDSJ = Uint2bytes(isensor2YSQDSJ);
            list.AddRange(sensor2YSQDSJ);
            UInt16 isensor1YSQDZS = UInt16.Parse(txbSensor1YSQDZS.Text);
            byte[] sensor1YSQDZS = Uint2bytes(isensor1YSQDZS);
            list.AddRange(sensor1YSQDZS);
            UInt16 isensor2YSQDZS =UInt16.Parse(txbSensor2YSQDZS.Text);
            byte[] sensor2YSQDZS = Uint2bytes(isensor2YSQDZS);
            list.AddRange(sensor2YSQDZS);
            UInt16 isensor1QDYXSJ = UInt16.Parse(txbSensor1QDYXSJ.Text);
            byte[] sensor1QDYXSJ = Uint2bytes(isensor1QDYXSJ);
            list.AddRange(sensor1QDYXSJ);
            UInt16 isensor2QDYXSJ = UInt16.Parse(txbSensor2QDYXSJ.Text);
            byte[] sensor2QDYXSJ = Uint2bytes(isensor2QDYXSJ);
            list.AddRange(sensor2QDYXSJ);
            UInt16 iMargdisplay = UInt16.Parse(txbSensorMargDisply.Text);
            byte[] Margdisplay = Uint2bytes(iMargdisplay);
            list.AddRange(Margdisplay);
            UInt16 iMsgBack = UInt16.Parse(txbSensorMsgBack.Text);
            byte[] MsgBack = Uint2bytes(iMsgBack);
            list.AddRange(MsgBack);
            #endregion
            string strTopic = this.textBoxtopic.Text.Trim();// this.textBoxtopic.Text + "0";
            if (strTopic.Length < 14)
            {
                strTopic = strTopic.PadRight(14);
            }
            byte[] bTopic = System.Text.Encoding.Default.GetBytes(strTopic);
            list.AddRange(bTopic);
            string strDeviceId = this.textBoxDeviceId.Text;
            if (strDeviceId.Length < 32)
            {
                strDeviceId = strDeviceId.PadRight(32);
            }
            byte[] bDeviceId = System.Text.Encoding.Default.GetBytes(strDeviceId);
            list.AddRange(bDeviceId);
            byte[] crc16 = TimestampHelper.ToModbus(list.ToArray());
            list.AddRange(crc16);
            string text = "";
            foreach(byte b in list)
            {

                text = text + b.ToString("X2") + " ";
            }
            lLogWrite.WriteLog("写入:"+text);
            return list.ToArray();
        }

        private void buttonFind_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "*.bin|*.BIN";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
               this.txtBoxFile.Text= dlg.FileName;
            }

        }

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtBoxFile.Text))
            {
                MessageBox.Show("请输入升级文件", "提示", MessageBoxButtons.OK);
                return;
            }
            if (!File.Exists(txtBoxFile.Text))
            {
                MessageBox.Show("所选升级文件不存在", "提示", MessageBoxButtons.OK);
                return;
            }
            Thread th = new Thread(UpdateHardNew);
            th.IsBackground = true;
            th.Start();
            while (th.IsAlive)
            {
                Application.DoEvents();
            }
            MessageBox.Show("升级完毕", "提示", MessageBoxButtons.OK);

        }
        //固件升级
        private void UpdateHard()
        {
            List<byte> fileByte = new List<byte>();
            fileByte.Add(0XAA);
            int file_len;//bin文件长度
            int addr = 0;//地址从0x00000000开始https://blog.csdn.net/woddle/article/details/102525606
            int count = 0;//换行显示计数
            byte[] binchar = new byte[] { };
            FileStream Myfile = new FileStream(txtBoxFile.Text, FileMode.Open, FileAccess.Read);
            BinaryReader binreader = new BinaryReader(Myfile);
            file_len = (int)Myfile.Length+1;//获取bin文件长度
            StringBuilder str = new StringBuilder();
            binchar = binreader.ReadBytes(file_len);
            fileByte.AddRange(binchar);
            //包大小
            int packetSize = 32;
            //包数量
            int packetCount = (int)(file_len / packetSize);
            //最后一个包的大小
            int lastPacketData = file_len - packetCount * packetSize;
            byte[] data = new byte[packetSize];
            byte[] crc16 = TimestampHelper.ToModbus(binchar);
            //先发一首帧   
            List<byte> list = new List<byte>();
            list.AddRange(new byte[] { 0XFF, 0X46, 0XC1, 0XB2 });
            this.sendCmd(list.ToArray());
            System.Threading.Thread.Sleep(3000);
            foreach (byte j in fileByte.ToArray())
            {
                if (count == packetSize)
                {
                    list.Clear(); ;
                    list.AddRange(data);
                    this.sendCmd(list.ToArray());
                    count = 0;
                    data[count] = j;
                    count++;
                }
                else
                {
                    data[count] = j;
                    count++;
                }
            }
            list.Clear();
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    list.Add(data[i]);
                }
                this.sendCmd(list.ToArray());
                System.Threading.Thread.Sleep(500);
                this.sendCmd(crc16);
            }
            //if (count % 16 == 0)
            //{
            //    count = 0;
            //    if (addr > 0)
            //        str.Append("\r\n");
            //    str.Append(addr.ToString("x8") + "      ");
            //    addr++;
            //}
            //str.Append(j.ToString("X2") + " ");
            //if (count == 8)
            //    str.Append("  ");
            //count++;
            //textBox1.Text = str.ToString();
            binreader.Close();
        }
        //固件升级 分包+双向确认
        private void UpdateHardNew()
        {
            List<byte> fileByte = new List<byte>();
            int file_len;//bin文件长度
            int addr = 0;//地址从0x00
            int count = 0;//换行显示计数
            byte[] binchar = new byte[] { };
            FileStream Myfile = new FileStream(txtBoxFile.Text, FileMode.Open, FileAccess.Read);
            BinaryReader binreader = new BinaryReader(Myfile);
            file_len = (int)Myfile.Length + 2;//获取bin文件长度
            StringBuilder str = new StringBuilder();
            binchar = binreader.ReadBytes(file_len);
            fileByte.AddRange(binchar);
            byte[] crc16 = TimestampHelper.ToModbus(binchar);
            fileByte.AddRange(crc16);
            //包大小
            int packetSize = 1000;
            //包数量
            int packetCount = (int)(file_len / packetSize);
            //最后一个包的大小 
            int lastPacketData = file_len - packetCount * packetSize;
            if (lastPacketData > 0)
                packetCount++;
            //包序列号
            int sn = 2;
            byte[] data = new byte[packetSize];
            //先发一首帧               
            byte[] bSize = intToBytes(file_len);
            //跳转指令          
            List<byte> list = new List<byte>();
            list.AddRange(new byte[] { 0XFF, 0X46, 0XC1, 0XB2 });
            SendPublic(list.ToArray());
            System.Threading.Thread.Sleep(3000);
            bool isReady = ReadReadyOK();
            if (!isReady)
            {
                Invoke(UpdataMessageHandle, "下位机准备失败,无数据返回，请检查通信是否正常!", list.ToArray());
                return;
            }
            else
            {
                IsReady = false;
            }            
            list.Clear();
            //跳转指令
            list.AddRange(new byte[] { 0XAA, 0X01 });
            list.AddRange(intToBytes(5));//首帧固定5 帧头 包数 有效数据个数  总包数 程序总大小 CRC效验（第一条）
                                         //   AA    01     X1  X2            Y1          Z1 Z2 Z3 Z4   CRC1 CRC2
            list.Add((byte)packetCount);
            list.AddRange(BitConverter.GetBytes(file_len).Reverse());
            crc16 = TimestampHelper.ToModbus(list.ToArray());
            list.AddRange(crc16);
            SendPublic(list.ToArray());
            string strLog = "";
            int sSize = 0;
            foreach (byte b in list)
            {
                strLog = strLog + b.ToString("X2") + " ";
                sSize++;
            }
            lLogWrite.WriteLog(string.Format("Send:{0}|{1}", sSize.ToString(), strLog));
            System.Threading.Thread.Sleep(1000);
            Invoke(UpdataMsgHandle, string.Format("文件大小:{0}文件分包个数:{1}", file_len, packetCount));
            int retryCount = 0;
            int errorCode = 0;
            while (ReadComReceive(out errorCode) > 1 && retryCount < 5)
            {
                System.Threading.Thread.Sleep(500);
                SendPublic(list.ToArray());
                lLogWrite.WriteLog(string.Format("Send Retry:", sSize.ToString(), strLog));
                retryCount++;
            }
            if (retryCount > 4)
            {
                Invoke(UpdataMsgHandle, "第1包数据发送有误，请检查通信是否正常!");
                return;
            }
            if (errorCode > 0)
            {
                Invoke(UpdataMsgHandle, "无数据返回，请检查通信是否正常!");
                return;
            }

            foreach (byte j in fileByte.ToArray())
            {
                if (count == packetSize)
                {
                    list.Clear();
                    list.Add(0XAA);
                    list.Add((byte)sn);
                    list.AddRange(intToBytes(packetSize));
                    list.AddRange(data);
                    crc16 = TimestampHelper.ToModbus(list.ToArray());
                    list.AddRange(crc16);
                    SendPublic(list.ToArray());
                    strLog = "";
                    sSize = 0;
                    foreach (byte b in list)
                    {
                        strLog = strLog + b.ToString("X2") + " ";
                        sSize++;
                    }
                    lLogWrite.WriteLog(string.Format("Send:{0}|{1}", sSize.ToString(), strLog));
                    System.Threading.Thread.Sleep(1000);
                    retryCount = 0;
                    errorCode = 0;
                    while (ReadComReceive(out errorCode) > 1 && retryCount < 5)
                    {
                        System.Threading.Thread.Sleep(500);
                        SendPublic(list.ToArray());
                        lLogWrite.WriteLog(string.Format("Send Retry:{0}|{1}", sSize.ToString(), strLog));
                        retryCount++;

                    }
                    if (retryCount > 4)
                    {
                        Invoke(UpdataMsgHandle, string.Format("第{0}包数据发送有误，请检查通信是否正常!", sn.ToString()));
                        return;
                    }
                    if (errorCode > 0)
                    {
                        Invoke(UpdataMsgHandle, "无数据返回，请检查通信是否正常!");
                        return;
                    }
                    Invoke(UpdataMsgHandle, string.Format("第{0}包数据发送成功...", sn.ToString()));
                    lLogWrite.WriteLog(string.Format("第{0}包数据发送成功...", sn.ToString()));
                    sn++;
                    count = 0;
                    data[count] = j;
                    count++;
                }
                else
                {
                    data[count] = j;
                    count++;
                }
            }
            list.Clear();
            if (count > 0)
            {
                list.Add(0XAA);
                list.Add((byte)sn);
                list.AddRange(intToBytes(count));
                for (int i = 0; i < count; i++)
                {
                    list.Add(data[i]);
                }
                crc16 = TimestampHelper.ToModbus(list.ToArray());
                list.AddRange(crc16);
                SendPublic(list.ToArray());
                strLog = "";
                sSize = 0;
                foreach (byte b in list)
                {
                    strLog = strLog + b.ToString("X2") + " ";
                    sSize++;
                }
                lLogWrite.WriteLog(string.Format("Send:{0}|{1}", sSize.ToString(), strLog));
                System.Threading.Thread.Sleep(1000);
                retryCount = 0;
                errorCode = 0;
                while (ReadComReceive(out errorCode) > 1 && retryCount < 5)
                {
                    System.Threading.Thread.Sleep(500);
                    SendPublic(list.ToArray());
                    lLogWrite.WriteLog(string.Format("Send Retry:{0}|{1}", sSize.ToString(), strLog));
                }
                if (retryCount > 4)
                {
                    Invoke(UpdataMsgHandle, string.Format("第{0}包数据发送有误，请检查通信是否正常!", sn.ToString()));
                    return;
                }
                if (errorCode > 0)
                {
                    Invoke(UpdataMsgHandle, "无数据返回，请检查通信是否正常!", list.ToArray());
                    return;
                }
                Invoke(UpdataMsgHandle, string.Format("第{0}包数据发送成功.", sn.ToString()));
            }
            binreader.Close();
            Invoke(UpdataMsgHandle, "升级完毕!");

        }
        private int ReadComReceive(out int error)
        {
            error = 0;
            int rel_code = 2;
            try
            {
                int retryCount = 0;
                while (IsOk < 0 && retryCount < 20)
                {
                    System.Threading.Thread.Sleep(1000);
                    retryCount++;
                }
                if (IsOk > 0)
                {
                    rel_code = IsOk;
                }
                else
                {
                    rel_code = -1;//通信异常
                    error = 1;
                }
            }
            catch (Exception ex)
            {
                lLogWrite.WriteLog("读取出错:" + ex.ToString());
            }

            return rel_code;
        }
        /// <summary>
        /// 2023.8.16 解决flag=3出现前发包造成升级失败问题
        /// </summary>
        /// <returns></returns>
        private bool ReadReadyOK()
        {
            bool rel = false;
            try
            {
                int retryCount = 0;
                while (!IsReady && retryCount < 10)
                {
                    System.Threading.Thread.Sleep(1000);
                    retryCount++;
                }
                if (IsReady)
                {
                    rel = true;
                }
                else
                {
                    rel = false;
                }
            }
            catch (Exception ex)
            {
                lLogWrite.WriteLog("读取出错:" + ex.ToString());
            }

            return rel;

        }
        /// <summary>
        /// int16 to byte[]
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public byte[] intToBytes(int value)
        {
            byte[] src = new byte[2];
            src[0] = (byte)((value >> 8) & 0xFF);
            src[1] = (byte)(value & 0xFF);
            return src;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            List<byte> list = new List<byte>();
            list.InsertRange(0, new byte[] { 0XFF, 0X48, 0X40, 0X76 });
            string text = "";
            foreach (byte b in list)
            {
                text = text + b.ToString("X2") + " ";
            }
            lLogWrite.WriteLog("设备重启:" + text);
            this.sendCmd(list.ToArray());
            list.Clear();  
        }

        private void buttonGetYlzh_Click(object sender, EventArgs e)
        {

        }

        private void YTdlgHardInfo_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("系统退出工作系统将停止远程终端配置或升级，确定要关闭吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
            {
                e.Cancel = true;
            }          
            if (mqttClient != null && mqttClient.IsConnected)
            {
                IsClose = true;
                mqttClient.DisconnectAsync();
                mqttClient.Dispose();
                mqttClient = null;                
            }          
        }

        private void btnAdmin_Click(object sender, EventArgs e)
        {
            if (btnAdmin.Text == "高级功能")
            {
                Verify dlg = new Verify();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    this.panelHide.Height = 226;
                    btnAdmin.Text = "退出高级";
                }
                else
                    return;
            }
            else
            {
                this.panelHide.Height = 6;
                btnAdmin.Text = "高级功能";
            }
        }

        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Excel files(*.xls;*.xlsx)|*.xls;*.xlsx";
            dlg.FilterIndex = 0;
            dlg.RestoreDirectory = true;
            dlg.CreatePrompt = true;
            dlg.Title = "保存为Excel文件";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string filName = dlg.FileName;
                DataTable dt = ParaFromTextBox();
                if (dt != null)
                {
                    if (ExcelUtli.ExcelOpr.DataTableToExcel(dt, filName) < 0)
                    {
                        MessageBox.Show("保存失败", "提示");
                    }
                    else
                    {
                        MessageBox.Show("保存成功", "提示");
                    }
                }
               
            }
        }
        private DataTable ParaFromTextBox()
        {           
            DataTable _dtSource = new DataTable();
            _dtSource.Columns.Add(new DataColumn("SetPara"));
            _dtSource.Columns.Add(new DataColumn("SetVal"));
            DataRow dr;
            dr = _dtSource.NewRow();
            dr["SetPara"] = "网关MAC";
            dr["SetVal"] = textBoxGateWayMAC.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1MAC";
            dr["SetVal"] = this.textBoxSensor1Mac.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2MAC";
            dr["SetVal"] = this.textBoxSensor2Mac.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "网关地址";
            dr["SetVal"] = textBoxGateWayAdd.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1启用";
            dr["SetVal"] = textBoxSensor1Status.Text.Trim();
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2启用";
            dr["SetVal"] = textBoxSensor2Status.Text.Trim();
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1检测时间";
            dr["SetVal"] = textBoxSensor1Time.Text.Trim();
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2检测时间";
            dr["SetVal"] = textBoxSensor2Times.Text.Trim();
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "伺服电机1启用";
            dr["SetVal"] = textBoxDJ1Status.Text.Trim();
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();   
            dr["SetPara"] = "伺服电机2启用";
            dr["SetVal"] = textBoxDJ2Status.Text.Trim();
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "伺服电机1正反转";
            dr["SetVal"] = textBoxDJ1Pos.Text.Trim();
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "伺服电机2正反转";
            dr["SetVal"] = textBoxDJ2Pos.Text.Trim();
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "伺服电机1转速";
            dr["SetVal"] = textBoxDJ1Speed.Text.Trim();
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "伺服电机2转速";
            dr["SetVal"] = textBoxDJ2Speed.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1系数";
            dr["SetVal"] = textBoxSensor1Value.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2系数";
            dr["SetVal"] = textBoxSensor2Value.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "油路转换间隔";
            dr["SetVal"] = textBoxYlzh.Text;
            _dtSource.Rows.Add(dr);

            #region 参数调整部分
            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1温度系数";
            dr["SetVal"] = txbSensor1Temper.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2温度系数";
            dr["SetVal"] = txbSensor2Temper.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1粘温曲线系数A";
            dr["SetVal"] = txbSensor1VisXa.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1粘温曲线系数B";
            dr["SetVal"] = txbSensor1VisXb.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2粘温曲线系数A";
            dr["SetVal"] = txbSensor2VisXa.Text;

            _dtSource.Rows.Add(dr);
            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2粘温曲线系数B";
            dr["SetVal"] = txbSensor2VisXb.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1粘度曲线比例";
            dr["SetVal"] = txbSensor1VisBl.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2粘度曲线比例";
            dr["SetVal"] = txbSensor2VisBl.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1粘度系数";
            dr["SetVal"] = txbSensor1Vis.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2粘度系数";
            dr["SetVal"] = txbSensor2Vis.Text;

            _dtSource.Rows.Add(dr);
            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1密度系数";
            dr["SetVal"] = txbSensor1Midu.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2密度系数";
            dr["SetVal"] = txbSensor2Midu.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1水活性系数";
            dr["SetVal"] = txbSensor1AW.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2水活性系数";
            dr["SetVal"] = txbSensor2AW.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1水分系数";
            dr["SetVal"] = txbSensor1PPM.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2水分系数";
            dr["SetVal"] = txbSensor2PPM.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1含水率系数";
            dr["SetVal"] = txbSensor1Hsl.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2含水率系数";
            dr["SetVal"] = txbSensor2Hsl.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1介电系数";
            dr["SetVal"] = txbSensor1Jdcs.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2介电系数";
            dr["SetVal"] = txbSensor2Jdcs.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1延时启动时间";
            dr["SetVal"] = txbSensor1YSQDSJ.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2延时启动时间";
            dr["SetVal"] = txbSensor2YSQDSJ.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1延时启动转速";
            dr["SetVal"] = txbSensor1YSQDZS.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2延时启动转速";
            dr["SetVal"] = txbSensor2YSQDZS.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器1启动运行时间";
            dr["SetVal"] = txbSensor1QDYXSJ.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "传感器2启动运行时间";
            dr["SetVal"] = txbSensor2QDYXSJ.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "高级功能显示";
            dr["SetVal"] = txbSensorMargDisply.Text;
            _dtSource.Rows.Add(dr);

            dr = _dtSource.NewRow();
            dr["SetPara"] = "调试信息回传";
            dr["SetVal"] = txbSensorMsgBack.Text;
            _dtSource.Rows.Add(dr);
            #endregion
            dr = _dtSource.NewRow();
            dr["SetPara"] = "Topic";
            dr["SetVal"] = textBoxtopic.Text;
            _dtSource.Rows.Add(dr);
            dr = _dtSource.NewRow();
            dr["SetPara"] = "DeviceId";
            dr["SetVal"] = textBoxDeviceId.Text;
            _dtSource.Rows.Add(dr);
            return _dtSource;
        }
        private void btnLoadConfig_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Excel files(*.xls;*.xlsx)|*.xls;*.xlsx|All files (*.*)|*.*";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string filName = dlg.FileName;
                //MessageBox.Show(filName.ToString());
                DataTable dt =ExcelUtli.ExcelOpr.ReadToTableCheckDateTime(dlg.FileName.ToString());
                if (dt != null)
                    LoadParaFromDt(dt);
                else
                    MessageBox.Show("加载出错，请查看日志文件");
            }
        }

        private void LoadParaFromDt(DataTable dt)
        {
            foreach (DataRow dr in dt.Rows)
            {
                switch (dr["SetPara"].ToString())
                {
                    case "网关MAC":textBoxGateWayMAC.Text = dr["SetVal"].ToString();break;
                    case "传感器1MAC":textBoxSensor1Mac.Text= dr["SetVal"].ToString(); break;
                    case "传感器2MAC":textBoxSensor2Mac.Text = dr["SetVal"].ToString(); break;
                    case "网关地址":textBoxGateWayAdd.Text = dr["SetVal"].ToString(); break;
                    case "传感器1启用":textBoxSensor1Status.Text = dr["SetVal"].ToString(); break;
                    case "传感器2启用":textBoxSensor2Status.Text = dr["SetVal"].ToString(); break;
                    case "传感器1检测时间":textBoxSensor1Time.Text = dr["SetVal"].ToString(); break;
                    case "传感器2检测时间":textBoxSensor2Times.Text = dr["SetVal"].ToString(); break;
                    case "伺服电机1启用":textBoxDJ1Status.Text= dr["SetVal"].ToString(); break;
                    case "伺服电机2启用":textBoxDJ2Status.Text = dr["SetVal"].ToString(); break;
                    case "伺服电机1正反转":textBoxDJ1Pos.Text = dr["SetVal"].ToString(); break;
                    case "伺服电机2正反转":textBoxDJ2Pos.Text = dr["SetVal"].ToString(); break;
                    case "伺服电机1转速":textBoxDJ1Speed.Text = dr["SetVal"].ToString(); break;
                    case "伺服电机2转速":textBoxDJ2Speed.Text = dr["SetVal"].ToString(); break;
                    case "传感器1系数":textBoxSensor1Value.Text = dr["SetVal"].ToString(); break;
                    case "传感器2系数":textBoxSensor2Value.Text = dr["SetVal"].ToString(); break;
                    case "油路转换间隔":textBoxYlzh.Text = dr["SetVal"].ToString(); break;
                    case "传感器1温度系数": txbSensor1Temper.Text = dr["SetVal"].ToString(); break;
                    case "传感器2温度系数":txbSensor2Temper.Text = dr["SetVal"].ToString(); break;
                    case "传感器1粘温曲线系数A":txbSensor1VisXa.Text = dr["SetVal"].ToString(); break;
                    case "传感器1粘温曲线系数B":txbSensor1VisXb.Text = dr["SetVal"].ToString(); break;
                    case "传感器2粘温曲线系数A":txbSensor2VisXa.Text = dr["SetVal"].ToString(); break;
                    case "传感器2粘温曲线系数B": txbSensor2VisXb.Text = dr["SetVal"].ToString(); break;
                    case "传感器1粘度曲线比例": txbSensor1VisBl.Text = dr["SetVal"].ToString(); break;
                    case "传感器2粘度曲线比例": txbSensor2VisBl.Text = dr["SetVal"].ToString(); break;
                    case "传感器1粘度系数":txbSensor1Vis.Text = dr["SetVal"].ToString(); break;
                    case "传感器2粘度系数": txbSensor2Vis.Text = dr["SetVal"].ToString(); break;
                    case "传感器1密度系数": txbSensor1Midu.Text = dr["SetVal"].ToString(); break;
                    case "传感器2密度系数":txbSensor2Midu.Text = dr["SetVal"].ToString(); break;
                    case "传感器1水活性系数": txbSensor1AW.Text = dr["SetVal"].ToString(); break;
                    case "传感器2水活性系数":txbSensor2AW.Text = dr["SetVal"].ToString(); break;
                    case "传感器1水分系数":txbSensor1PPM.Text = dr["SetVal"].ToString(); break;
                    case "传感器2水分系数":txbSensor2PPM.Text = dr["SetVal"].ToString(); break;
                    case "传感器1含水率系数":txbSensor1Hsl.Text = dr["SetVal"].ToString(); break;
                    case "传感器2含水率系数":txbSensor2Hsl.Text = dr["SetVal"].ToString(); break;
                    case "传感器1介电系数":txbSensor1Jdcs.Text = dr["SetVal"].ToString(); break;
                    case "传感器2介电系数":txbSensor2Jdcs.Text = dr["SetVal"].ToString(); break;
                    case "传感器1延时启动时间":txbSensor1YSQDSJ.Text = dr["SetVal"].ToString(); break;
                    case "传感器2延时启动时间":txbSensor2YSQDSJ.Text = dr["SetVal"].ToString(); break;
                    case "传感器1延时启动转速": txbSensor1YSQDZS.Text = dr["SetVal"].ToString(); break;
                    case "传感器2延时启动转速":txbSensor2YSQDZS.Text = dr["SetVal"].ToString(); break;
                    case "传感器1启动运行时间":txbSensor1QDYXSJ.Text = dr["SetVal"].ToString(); break;
                    case "传感器2启动运行时间": txbSensor2QDYXSJ.Text = dr["SetVal"].ToString(); break;
                    case "高级功能显示":txbSensorMargDisply.Text = dr["SetVal"].ToString(); break;
                    case "调试信息回传": txbSensorMsgBack.Text = dr["SetVal"].ToString(); break;
                    case "Topic": textBoxtopic.Text= dr["SetVal"].ToString(); break;
                    case "DeviceId":textBoxDeviceId.Text= dr["SetVal"].ToString(); break;
                }
            }
        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void comboBoxDevice_SelectedValueChanged(object sender, EventArgs e)
        {
            if (comboBoxDevice.SelectedIndex > 0)
            {
                textBoxSubscribe.Text = comboBoxDevice.SelectedValue.ToString();                
            }
        }
    }
}



